package wailsutil

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

type FileLoaderServer struct {
	http.Handler
}

func NewFileLoader() *FileLoaderServer {
	return &FileLoaderServer{}
}

func (h *FileLoaderServer) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	var err error
	requestedFilename := strings.TrimPrefix(req.URL.Path, "/")
	//println("Requesting file:", requestedFilename)
	fileData, err := os.ReadFile(requestedFilename)
	if err != nil {
		res.WriteHeader(http.StatusBadRequest)
		res.Write([]byte(fmt.Sprintf("Could not load file %s", requestedFilename)))
		return
	}

	// 设置正确的 Content-Type
	ext := filepath.Ext(requestedFilename)
	switch ext {
	case ".css":
		res.Header().Set("Content-Type", "text/css")
	case ".js":
		res.Header().Set("Content-Type", "application/javascript")
	case ".html":
		res.Header().Set("Content-Type", "text/html")
	case ".png":
		res.Header().Set("Content-Type", "image/png")
	case ".jpg", ".jpeg":
		res.Header().Set("Content-Type", "image/jpeg")
	case ".bmp":
		res.Header().Set("Content-Type", "image/bmp")
	case ".gif":
		res.Header().Set("Content-Type", "image/gif")
	default:
		res.Header().Set("Content-Type", "application/octet-stream")
	}

	res.Write(fileData)
}
